

import 'package:erp/Entity/CustomerType.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/CustomerTypeStore.dart';
import 'package:erp/UI/CodeResources/Localization.dart';
import 'package:erp/UI/Components/EventfulState.dart';
import 'package:erp/UI/Components/ListDividerGenerator.dart';
import 'package:erp/UI/Components/LogoScaffold.dart';
import 'package:erp/UI/Components/MessageDialog.dart';
import 'package:erp/UI/Components/QuestionDialog.dart';
import 'package:erp/global.dart';
import 'package:flutter/material.dart';

class CustomerTypePage extends StatefulWidget {
  bool isSelectionMode;
  CustomerTypePage({this.isSelectionMode = false});

  @override
  State<StatefulWidget> createState() => CustomerTypePageState();
}

class CustomerTypePageState extends EventfulState<CustomerTypePage> {

  @override
  void initState() {
    eventIds = [
      globalBus.subscribe(Events.CUSTOMER_TYPE_SELECT_SUCCESS, (bus, data){setState(() {});}),
      globalBus.subscribe(Events.CUSTOMER_TYPE_INSERT_SUCCESS, (bus, data){setState(() {});}),
      globalBus.subscribe(Events.CUSTOMER_TYPE_UPDATE_SUCCESS, (bus, data){setState(() {});}),
      globalBus.subscribe(Events.CUSTOMER_TYPE_DELETE_SUCCESS, (bus, data){setState(() {});}),
      globalBus.subscribe(Events.CUSTOMER_TYPE_SELECT_ERROR, (bus, error) async {
        await showMessageDialog(context, title: "ئوقۇش مەغلۇپ بولدى", content: error.toString());
      }),
      globalBus.subscribe(Events.CUSTOMER_TYPE_INSERT_ERROR, (bus, error) async {
        await showMessageDialog(context, title: "قوشۇش مەغلۇپ بولدى", content: error.toString());
      }),
      globalBus.subscribe(Events.CUSTOMER_TYPE_UPDATE_ERROR, (bus, error) async {
        await showMessageDialog(context, title: "ئۆزگەرتىش مەغلۇپ بولدى", content: error.toString());
      }),
      globalBus.subscribe(Events.CUSTOMER_TYPE_DELETE_ERROR, (bus, error) async {
        await showMessageDialog(context, title: "ئۆچۈرۈش مەغلۇپ بولدى", content: error.toString());
      }),
    ];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return LogoScaffold(
        heroName: "CustomerTypeHero",
        assetsLogoName: "assets/pictures/salesman.png",
        title: "خىرىدار تۈرىنى باشقۇرۇش",
        contentDelegate: SliverChildListDelegate(ListDividerGenerator(CustomerTypeStore.customerTypes.map((item) => buildListItem(context, item)).toList(), Divider()).items),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () async {
            var data = CustomerType();
            var isOkay = await showEditDialog(context, data);
            if (isOkay){
              globalBus.publish(Events.CUSTOMER_TYPE_INSERT_REQUEST, data);
            }
          },
        ),
    );
  }

  Widget buildListItem(BuildContext context, CustomerType data){
    return ListTile(
      title: Text(data.name),
      subtitle: Text(data.memo),
      leading: Image.asset("assets/pictures/salesman.png", width: 40.0, height: 40.0,),
      trailing: Wrap(
        direction: Axis.horizontal,
        children: <Widget>[
          IconButton(icon: Icon(Icons.edit), onPressed: () async {
            var tempData = CustomerType.fromJson(data.toJson());
            var isOkay = await showEditDialog(context, tempData);
            if (isOkay){
              globalBus.publish(Events.CUSTOMER_TYPE_UPDATE_REQUEST, tempData);
            }
          }),
          IconButton(icon: Icon(Icons.delete_forever), onPressed: () async {
            var result = await showQuestionDialog(context, title: "ئەسكەرتىش", content: "سىز راستىنلا بۇ تۈرنى ئۆچۈرۋەتمەكچىمۇ؟");
            if (result ?? false) {
              globalBus.publish(Events.CUSTOMER_TYPE_DELETE_REQUEST, data);
            }
          }),
        ],
      ),
      onTap: (){
        if (widget.isSelectionMode) Navigator.of(context).pop(data);
      },
    );
  }

  Future<bool> showEditDialog(BuildContext context, CustomerType data) async {
    var locale = AppLocalizations.of(context);
    var nameController = TextEditingController(text: data?.name ?? "");
    var memoController = TextEditingController(text: data?.memo ?? "");

    return await showDialog(context: context, builder: (context) => Directionality(
      textDirection: locale.textDirection,
      child: AlertDialog(
        title: Text("ئىشلەتكۈچى تۈرى"),
        contentPadding: EdgeInsets.all(25.0),
        content: Container(
          width: 300.0,
          child: Wrap(
            children: <Widget>[
              TextField(
                decoration: InputDecoration(
                  labelText: "تۈر ئىسمى",
                  hintText: "تۈر ئىسمىنى كىرگۈزۈڭ"
                ),
                controller: nameController,
              ),
              TextField(
                decoration: InputDecoration(
                  labelText: "قوشۇمچە",
                  hintText: "قوشۇمچە ئۇچۇرى"
                ),
                controller: memoController,
              ),
            ],
          ),
        ),
        actions: <Widget>[
          FlatButton(
            child: Text("جەزىملەشتۈرۈش"),
            onPressed: () async {
              if (nameController.text.isEmpty){
                await showMessageDialog(context, title: "ئەسكەرتىش", content: "ئىسىم قۇرۇق قالسا بولمايدۇ");
                return;
              }
              data.name = nameController.text;
              data.memo = memoController.text;

              Navigator.of(context).pop(true);
            },
          ),
          FlatButton(
            child: Text("بىكار قىلىش"),
            onPressed: (){
              Navigator.of(context).pop(false);
            },
          ),
        ],
      )),
      barrierDismissible: false
    ) ?? false;
  }
}

